from django.db import models
from user.models import User
from datetime import datetime
from recharge.models import Member

import utils


class Order(models.Model):
    """订单模型"""
    status_choices = (
        (0, '未支付'),
        (1, '已支付'),
        (2, '已取消'),
        (3, '超时取消'),
    )
    pay_choices = (
        (1, '支付宝支付'),
        (2, '微信支付'),
        (3, '银行卡支付'),
    )
    subject = models.CharField(max_length=150, verbose_name="订单标题")
    total_amount = models.DecimalField(max_digits=10, decimal_places=2, verbose_name="订单总价", default=0)
    out_trade_no = models.CharField(max_length=64, verbose_name="订单号", unique=True)
    trade_no = models.CharField(max_length=64, null=True, verbose_name="流水号")
    order_status = models.SmallIntegerField(choices=status_choices, default=0, verbose_name="订单状态")
    pay_type = models.SmallIntegerField(choices=pay_choices, default=1, verbose_name="支付方式")
    pay_time = models.DateTimeField(null=True, verbose_name="支付时间")
    created_time = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_time = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    # 订单表和用户表关系分析: 一对多  订单是多的一方 一个用户可以下多个订单, 一个订单不能属于多个用户
    user = models.ForeignKey(to='user.User', related_name='order_user', on_delete=models.DO_NOTHING,
                             db_constraint=False,
                             verbose_name="下单用户")

    class Meta:
        verbose_name = "订单记录"
        verbose_name_plural = verbose_name

    def __str__(self):
        return "%s - ￥%s" % (self.subject, self.total_amount)

    @property
    def order_detail_list(self):
        data_list = []
        for item in self.order_details.all():
            data_list.append({
                "id": item.id,
                "price": item.price,
                "real_price": item.real_price,
            })
        return data_list


class OrderDetail(models.Model):
    """订单详情"""
    price = models.DecimalField(max_digits=6, decimal_places=2, verbose_name="会员原价")
    real_price = models.DecimalField(max_digits=6, decimal_places=2, verbose_name="会员实价")

    # 订单和订单详情表关系分析: 一对多 订单详情是多的一方  一个订单可以有多个订单详情, 一个订单详情不可以同时属于多个订单.
    order = models.ForeignKey(to='Order', related_name='order_details', on_delete=models.CASCADE, db_constraint=False,
                              verbose_name="订单")
    member = models.ForeignKey(to='recharge.Member', related_name='members', on_delete=models.CASCADE, db_constraint=False, verbose_name="充值当前的会员套餐")

    class Meta:
        verbose_name = "订单详情"
        verbose_name_plural = verbose_name

    def __str__(self):
        """str的健壮性校验"""
        try:
            return "%s的订单：%s" % (self.order.user.username, self.order.out_trade_no)
        except Exception as e:
            utils.log.error(str(e))
            return super().__str__()

    @property
    def member_dict(self):
        return {'buy_month': self.member.buy_month, 'give_data': self.member.give_day, 'is_give': self.member.is_give}

